/**
 * MyInterceptor.java
 * com.ebook.interceptors
 * Copyright (c) 2013, 公司版权所有.
*/

package com.ebook.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ebook.core.controller.support.ControllerContext;
import com.ebook.util.Constants;
import com.ebook.util.DateUtil;



/**
 * springmvc拦截器类
 * @author    潘吉友
 * @Date	 2013-3-13 	 
 */
public class CommonInterceptor implements HandlerInterceptor{
	
	private static final Log logger = LogFactory.getLog(CommonInterceptor.class); 

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception arg3)
			throws Exception {
		ControllerContext.clear();
		request.removeAttribute(Constants.REQUEST_BEGIN_TIME_ATTRIBUTE);
		request.removeAttribute(Constants.REQUEST_CONTROLLER_FINISH_TIME_ATTRIBUTE);		
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView arg3) throws Exception {
		request.setAttribute(Constants.REQUEST_CONTROLLER_FINISH_TIME_ATTRIBUTE, DateUtil.getCurrentMill());
		StringBuilder info = new StringBuilder();
		info.append("request url:{").append(request.getRequestURI()).append("} used time {")
		.append(DateUtil.getCurrentMill()- (Long) request.getAttribute(Constants.REQUEST_BEGIN_TIME_ATTRIBUTE))
		.append("} ms");
		logger.info(info.toString());
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception{
		request.setAttribute(Constants.REQUEST_BEGIN_TIME_ATTRIBUTE,DateUtil.getCurrentMill());
		ControllerContext.setRequest(request);
		return true;
	}

	


	

}

